package com.cjh.controller;

import com.cjh.entity.User;
import com.cjh.vo.ResultMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class UploadController {

    @PostMapping("/upload")
    public ResultMap upload(@RequestParam("uploadFile") MultipartFile uploadFile, HttpServletRequest request){

        String realPath=request.getSession().getServletContext().getRealPath("/uploadFile/");
        File directory=new File(realPath);
        if (!directory.exists()){
            directory.mkdirs();
        }
        String oldName=uploadFile.getOriginalFilename();
        String newName= UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf(".",oldName.length()));
        try {
            uploadFile.transferTo(new File(directory,newName));
            String filePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/uploadFile/"+newName;
            Map<String,Object> data=new HashMap<>();
            data.put("src",filePath);
            return new ResultMap<Map<String,Object>>(0,"上传图片请求",data);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultMap<String>(1,"上传图片请求","服务器异常");
        }

    }

    @PostMapping("/add")
    public ResultMap add(User user){
        System.out.println(user);
        if(!Objects.isNull(user)){
            return new ResultMap<User>(200,"表单提交请求",user,1);
        }
        return new ResultMap<String>(500,"表单提交请求","失败");
    }

    @PostMapping("/get")
    public ResultMap get(){
        User user=new User("cjh","123","http://localhost:8002/uploadFile/f439b417-5730-4b56-a9dc-6304436d280d.jpg");
        System.out.println(user);

        return new ResultMap<User>(200,"获取用户信息",user);
    }

    @DeleteMapping("/deleteFile/{fileName}")
    public String deleteFile(HttpServletRequest request,@PathVariable("fileName") String fileName){
        String realPath = request.getServletContext().getRealPath("/uploadFile/");
        File file=new File(realPath+fileName);
        if(file.exists()){
            file.delete();
        }
        return "success";
    }
}
